package com.hk.servlet.company;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hk.model.CompanyMessage;
import com.hk.model.ContactUs;
import com.hk.model.vo.Result;
import com.hk.service.IContactUsService;
import com.hk.service.impl.ContactUsServiceImpl;
import com.hk.utils.CharacterEncoding;
import com.hk.utils.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: zhe
 * @Date: 2021/6/15 16:43
 * @Statement: 通过Id查询当前联系我们信息并进行信息修改
 */
@WebServlet("/contactUs/ContactUsFindByIdOrUpdate")
public class ContactUsFindByIdOrUpdateServlet extends HttpServlet {

    IContactUsService iContactUsService = new ContactUsServiceImpl();

    /**
     * 通过Id查询当前联系我们信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        String id = Tool.nullToString(req.getParameter("id"));
        int intId = Tool.parseInt(id);
        ContactUs contactUs = iContactUsService.findById(intId);
        PrintWriter out = resp.getWriter();
        String toJSONString = JSONObject.toJSONString(contactUs);
        out.println(toJSONString);
        out.flush();
        out.close();

    }

    /**
     * 通过Id修改当前联系我们信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        BufferedReader reader = req.getReader();
        Gson gson = new Gson();
        ContactUs contactUs = gson.fromJson(reader, ContactUs.class);
        int update = iContactUsService.update(contactUs);
        PrintWriter out = resp.getWriter();
        Result result = new Result();
        if (update != 1) {
            result.setStatus(update);
            result.setMessage("error");
        } else {
            result.setStatus(update);
            result.setMessage("success");
        }
        String resultJSON = JSONObject.toJSONString(result);
        out.println(resultJSON);
        out.flush();
        out.close();

    }

}
